package com.hoelg.hgc;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hoelg.hgc.DAO.HGCUser;
import com.hoelg.hgc.constants.Utils;
import com.hoelg.hgc.webservices.ConnexionUtilisateur;

public class Login extends Activity implements OnClickListener {

	public ConnectToAppli task;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		initialyseUI();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_login, menu);
        return true;
    }
    
	public void initialyseUI(){
        setContentView(R.layout.activity_login);
		Button button = (Button)findViewById(R.id.connect);
		button.setOnClickListener(this);
	}
    
	protected void onResume(){
		super.onResume();
		HGCUser.dispose();
	}

	
	

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.connect:
			//verif q'on a bien le net
			if (!CheckConnectivity()){
				Toast toast = Toast.makeText(getApplicationContext(), "Vous devez etre connecte a Internet pour pouvoir utiliser l'application", Toast.LENGTH_SHORT);
				toast.show();
				return;
			}
			String login =  ((EditText)findViewById(R.id.etLogin)).getText().toString();
			String mdp = ((EditText)findViewById(R.id.etPwd)).getText().toString();
			task = new ConnectToAppli();
			task.execute(login, mdp);


		default:
			break;
		}
	}
	/**
	 * vérifie la connectivité de l'appareil
	 * @return true s'il y une connexion internet
	 */
	private boolean CheckConnectivity() {
		boolean isConnected = false;
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		for (int i = 0; i<netInfo.length; i++){
			if (netInfo[i] != null && netInfo[i].isConnectedOrConnecting()) {
				isConnected =  true;
				break;
			}
		}

		return isConnected;
	}

	
	
	
	
	
	@Override
	protected Dialog onCreateDialog(int id) {
		ProgressDialog dialog = new ProgressDialog(Login.this);
		dialog.setCancelable(true);
		dialog.setMessage("Tentative de connexion...");
		// set the progress to be horizontal
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		return dialog;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		initialyseUI();
		removeDialog(0);
	}

	//classe interne de gestion des taches de fond de la connexion
	public class ConnectToAppli extends AsyncTask<String, Void, Void> {

		@Override
		protected void onPreExecute() {
			//gestion de l'attente
			showDialog(0);
		}

		@Override
		protected void onPostExecute(final Void unused) {
			removeDialog(0);
			//connect();
			if (!Utils.isNullOrEmpty(HGCUser.getInstance().getLogin())){
				//lancement du menu
				Login.this.startActivity(new Intent(Login.this, MainActivity.class));
			}
			else{
				Toast toast = Toast.makeText(getApplicationContext(), "Identifiant et/ou mot de passe incorrect", Toast.LENGTH_SHORT);
				toast.show();
				return;
			}
		}

		@Override
		protected Void doInBackground(String... params) {
			try {
				ConnexionUtilisateur ws = new ConnexionUtilisateur(params[0], params[1]);

				ws.executeWebService();

				//String result = ws.getResultatWS();

			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// TODO Auto-generated method stub
			return null;
		}

	}
}
